package com.credithc.customers.dataservice.service.impl;

import com.credithc.customers.base.constants.CustomerConstants;
import com.credithc.customers.dataservice.Thread.OldDataThreadPoolExecutor;
import com.credithc.customers.dataservice.constants.SyncTypeEnum;
import com.credithc.customers.dataservice.mapper.CD.*;
import com.credithc.customers.dataservice.po.*;
import com.credithc.customers.dataservice.ro.CustomerAccountInfoRo;
import com.credithc.customers.dataservice.ro.CustomerProductInfoRo;
import com.credithc.customers.dataservice.ro.ProductInfoRo;
import com.credithc.customers.dataservice.service.OldCHDService;
import com.credithc.customers.dataservice.service.SyncDataService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.sql.Timestamp;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicReference;

@Service
@Slf4j
public class OldCHDServiceImpl implements OldCHDService {
    @Autowired
    private CommonMapper commonMapper;
    @Autowired
    private LesseeMapper lesseeMapper;
    @Autowired
    private ContractLoanMapper contractLoanMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private EntryBasicInfoMapper entryBasicInfoMapper;
    @Autowired
    private EntryProdInfoMapper entryProdInfoMapper;
    @Autowired
    private CHDProductMapper chdProductMapper;
    @Autowired
    private OldDataThreadPoolExecutor oldDataThreadPoolExecutor;
    @Autowired
    private SyncDataService syncDataService;
    @Override
    public void oldproduct(Integer start) {
        boolean f =true;
        Long num = null;
        if (start != null && start >0){
            num = Long.valueOf(start);
        }else {
            num = chdProductMapper.queryProductMaxId();
        }
        if (num == null){
            return;
        }
        AtomicReference<Long> vernier = new AtomicReference<>( num+10001);
        ExecutorService e = oldDataThreadPoolExecutor.getCustomThreadPoolExecutor();
        while (f) {
            e.execute(() -> {
                try {
                    if (vernier.get()>0){
                        vernier.set(vernier.get()-10000);
                    }
                    Example example = new Example(CHDproductinfoPO.class);
                    Example.Criteria criteria = example.createCriteria();
                    criteria.andBetween("id",vernier.get()-10000,vernier.get());
                    List<CHDproductinfoPO> chDproductinfoPOS = chdProductMapper.selectByExample(example);
                    if (chDproductinfoPOS.size() > 0) {
                        chDproductinfoPOS(chDproductinfoPOS);
                    }
                } catch (Exception e1) {
                    log.error(e1.getMessage());
                }
            });
            f = OldHyrDataServiceImpl.exit(f, vernier, e);
        }
    }

    private void chDproductinfoPOS(List<CHDproductinfoPO> chDproductinfoPOS) {
        for (CHDproductinfoPO c:chDproductinfoPOS) {
            ProductInfoRo productInfoRo = new ProductInfoRo();
            productInfoRo.setSyncType(SyncTypeEnum.NEW.getValue());
            productInfoRo.setDatabaseName("finance_lease_system");
            productInfoRo.setTableName("FL_Prod_Base");
            productInfoRo.setProductChannel("CHD");
            productInfoRo.setSubSystemSign("CHD");
            productInfoRo.setSystemSign("CHD");
            productInfoRo.setProductType(6+"");
            productInfoRo.setProductNo(c.getProdCode());
            productInfoRo.setTableKey(c.getId()+"");
            productInfoRo.setProductName(c.getProName());
            if (c.getCreatedAt()>0) {
                productInfoRo.setProductCreateTime(new Timestamp(c.getCreatedAt()));
            }
            syncDataService.syncProduct(productInfoRo);
        }
    }

    @Override
    public void oldaccount(Integer start) {
        boolean f =true;
        Long num = null;
        if (start != null && start >0){
            num = Long.valueOf(start);
        }else {
            num = contractMapper.queryProductMaxId();
        }
        if (num == null){
            return;
        }
        AtomicReference<Long> vernier = new AtomicReference<>( num+10001);
        ExecutorService e = oldDataThreadPoolExecutor.getCustomThreadPoolExecutor();
        while (f) {
            e.execute(() -> {
                try {
                    if (vernier.get()>0){
                        vernier.set(vernier.get()-10000);
                    }
                    Example example = new Example(CHDContractPO.class);
                    Example.Criteria criteria = example.createCriteria();
                    criteria.andBetween("id",vernier.get()-10000,vernier.get());
                    List<CHDContractPO> chdContractPOS = contractMapper.selectByExample(example);
                    if (chdContractPOS.size() > 0) {
                        chdAccountinfoPOS(chdContractPOS);
                    }
                } catch (Exception e1) {
                    log.error(e1.getMessage());
                }
            });
            f = OldHyrDataServiceImpl.exit(f, vernier, e);
        }
    }

    private void chdAccountinfoPOS(List<CHDContractPO> chdContractPOS) {
        for (CHDContractPO c:chdContractPOS) {

            CustomerAccountInfoRo customerAccountInfoRo = new CustomerAccountInfoRo();
            customerAccountInfoRo.setSyncType(SyncTypeEnum.NEW.getValue());
            customerAccountInfoRo.setSubSystemSign("CHD");
            customerAccountInfoRo.setSystemSign("CHD");
            try {
                customerAccountInfoRo.setAccountCreateTime((new Timestamp(Long.valueOf(c.getCreateAt()))));
            } catch (NumberFormatException e) {
              //  e.printStackTrace();
            }
            customerAccountInfoRo.setAccountType(CustomerConstants.CUSTOMER_ACCOUNT_TYPE_BANK_CARD);
            customerAccountInfoRo.setCustomerRole(CustomerConstants.CUSTOMER_ACCOUNT_TYPE_LOAN);
            Example e = new Example(CHDCommonPO.class);
            Example.Criteria criteria = e.createCriteria();
            criteria.andEqualTo("contractCode",c.getContractCode());
            CHDCommonPO chdCommon = null;
            try {
                chdCommon = commonMapper.selectOneByExample(e);
            } catch (Exception e1) {
                List<CHDCommonPO> chdCommonPOS = null;
                try {
                    chdCommonPOS = commonMapper.selectByExample(e);
                } catch (Exception e2) {
                }
                if (chdCommonPOS!=null && chdCommonPOS.size()>0) {
                    chdCommon = chdCommonPOS.get(chdCommonPOS.size() - 1);
                }
            }
            if (chdCommon != null ){
                Example l = new Example(CHDLesseePO.class);
                Example.Criteria lc = l.createCriteria();
                lc.andEqualTo("businessId",chdCommon.getId());
                CHDLesseePO chdLesseePO = null;
                try {
                    chdLesseePO = lesseeMapper.selectOneByExample(l);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
                if (chdLesseePO != null && StringUtils.isNotBlank(chdLesseePO.getCustomerNo())){
                    customerAccountInfoRo.setCustomerNo(chdLesseePO.getCustomerNo());
                    customerAccountInfoRo.setUserSourceId("CHD"+ chdLesseePO.getCustomerNo());
                    customerAccountInfoRo.setAccountStatus(CustomerConstants.STATUS_ACCOUNT_AVAILABLE);
                    if (StringUtils.isNotBlank(customerAccountInfoRo.getCustomerNo())){

                        if (StringUtils.isNotBlank(c.getPayAccount())) {
                            customerAccountInfoRo.setAccountNo(c.getPayAccount());
                            syncDataService.syncCustomerAccount(customerAccountInfoRo);
                        }
                        if (StringUtils.isNotBlank(c.getReceiAccount())) {
                            customerAccountInfoRo.setAccountNo(c.getReceiAccount());
                            syncDataService.syncCustomerAccount(customerAccountInfoRo);
                        }
                    }
                }
            }
        }
    }

    @Override
    public void oldorder(Integer start) {
        boolean f =true;
        Long num = null;
        if (start != null && start >0){
            num = Long.valueOf(start);
        }else {
            num = commonMapper.queryProductMaxId();
        }
        if (num == null){
            return;
        }
        AtomicReference<Long> vernier = new AtomicReference<>( num+10001);
        ExecutorService e = oldDataThreadPoolExecutor.getCustomThreadPoolExecutor();
        while (f) {
            e.execute(() -> {
                try {
                    if (vernier.get()>0){
                        vernier.set(vernier.get()-10000);
                    }
                    Example example = new Example(CHDCommonPO.class);
                    Example.Criteria criteria = example.createCriteria();
                    criteria.andEqualTo("systemType","CD");
                    criteria.andBetween("id",vernier.get()-10000,vernier.get());
                    List<CHDCommonPO> chdCommonPOS = commonMapper.selectByExample(example);
                    if (chdCommonPOS.size() > 0) {
                        bulidOrder(chdCommonPOS);
                    }
                } catch (Exception e1) {
                    log.error(e1.getMessage());
                }
            });
            f = OldHyrDataServiceImpl.exit(f, vernier, e);
        }
    }

    private void bulidOrder(List<CHDCommonPO> chdCommonPOS) {
        for (CHDCommonPO c : chdCommonPOS) {
            CustomerProductInfoRo customerProductInfoRo = new CustomerProductInfoRo();
            customerProductInfoRo.setDatabaseName("finance_lease_system");
            customerProductInfoRo.setTableName("fl_business_common");
            customerProductInfoRo.setSyncType(SyncTypeEnum.NEW.getValue());
            customerProductInfoRo.setSystemSign("CHD");
            customerProductInfoRo.setSubSystemSign("CHD");
            customerProductInfoRo.setProductSourceSystem("17");
            customerProductInfoRo.setProductStatus(CustomerProductInfoServiceImpl.getYZTStatus("CHD" + c.getBusiStatus()));
            customerProductInfoRo.setTableKey(c.getId());
            customerProductInfoRo.setProductNo(c.getProdPlan());
            Example l = new Example(CHDLesseePO.class);
            Example.Criteria lc = l.createCriteria();
            lc.andEqualTo("businessId", c.getId());
            CHDLesseePO chdLesseePO = null;
            try {
                chdLesseePO = lesseeMapper.selectOneByExample(l);
            } catch (Exception e) {
              //  e.printStackTrace();
            }
            if (chdLesseePO != null && StringUtils.isNotBlank(chdLesseePO.getCustomerNo())) {
                customerProductInfoRo.setCustomerNo(chdLesseePO.getCustomerNo());
                customerProductInfoRo.setUserResourceId("CHD" + chdLesseePO.getCustomerNo());
                Example example = new Example(CHDContractLoanPO.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("contractCode", c.getContractCode());
                CHDContractLoanPO chdContractLoanPO = null;
                try {
                    chdContractLoanPO = contractLoanMapper.selectOneByExample(example);
                } catch (Exception e) {
                   // e.printStackTrace();
                }
                if (chdContractLoanPO != null) {
                    customerProductInfoRo.setProductAmount(chdContractLoanPO.getLoanMoney());
                    if (chdContractLoanPO.getLoanDate() != null) {
                        customerProductInfoRo.setProductStartTime(new Timestamp(chdContractLoanPO.getLoanDate()));
                    }
                }
                Example example1 = new Example(CHDContractPO.class);
                Example.Criteria criteria1 = example1.createCriteria();
                criteria1.andEqualTo("contractCode", c.getContractCode());
                CHDContractPO chdContractPO = null;
                try {
                    chdContractPO = contractMapper.selectOneByExample(example1);
                } catch (Exception e) {
                   // e.printStackTrace();
                }
                if (chdContractPO != null && chdContractPO.getEndDate() != null) {
                    customerProductInfoRo.setProductEndTime(new Timestamp(chdContractPO.getEndDate()));
                }

                Example example2 = new Example(CHDEntryBasicInfoPO.class);
                Example.Criteria criteria2 = example2.createCriteria();
                criteria2.andEqualTo("businessId", c.getId());
                CHDEntryBasicInfoPO chdEntryBasicInfoPO = null;
                try {
                    chdEntryBasicInfoPO = entryBasicInfoMapper.selectOneByExample(example2);
                } catch (Exception e) {

                }
                if (chdEntryBasicInfoPO != null) {
                    Example example3 = new Example(CHDEntryProdInfoPO.class);
                    Example.Criteria criteria3 = example3.createCriteria();
                    criteria3.andEqualTo("entryId", chdEntryBasicInfoPO.getId());
                    criteria3.andEqualTo("prodPlanfrom", "C");
                    CHDEntryProdInfoPO chdEntryProdInfoPO = null;
                    try {
                        chdEntryProdInfoPO = entryProdInfoMapper.selectOneByExample(example3);
                    } catch (Exception e) {

                    }
                    if (chdEntryProdInfoPO != null && chdEntryProdInfoPO.getLessee_time() != null) {
                        customerProductInfoRo.setProductDeadline(chdEntryProdInfoPO.getLessee_time() * 30 + "");
                    }
                }
                if (StringUtils.isNotBlank(customerProductInfoRo.getCustomerNo()) && StringUtils.isNotBlank(customerProductInfoRo.getProductNo())) {
                    syncDataService.syncCustomerProduct(customerProductInfoRo);
                }
            }
        }
    }
}
